import React, { useState, useEffect, useCallback, useMemo } from 'react'

import { message, Table, Image, Button, Space, Tag, Row, Col, Popconfirm, Rate, Input, Select } from 'antd'
import { DeleteOutlined, FormOutlined, PlusOutlined, ImportOutlined, ExportOutlined } from '@ant-design/icons'
import { useNavigate, useSearchParams } from 'react-router-dom'
import axios from 'axios'

const { Search } = Input;
const { Option } = Select;

import request, { baseUrl } from '../../../utils/request'
// import { useStore, useSelector } from 'react-redux'

//请求数据链接
// import axios from 'axios'
// export const baseUrl = 'http://120.76.247.5:2001'

// const request = axios.create({   
//     baseURL: baseUrl + '/api',
// })


const List = () => {
    const navigate = useNavigate();
    // 分页功能
    const [urlParams, setUrlParams] = useSearchParams()
    const [keyword, setKeyword] = useState(urlParams.get('keyword') || '');
    console.log('keyword', keyword);
    const [params, setParams] = useState({
        // 解决数据类型为string引起的bug
        page: Number(urlParams.get('page')) || 1,
        size: Number(urlParams.get('size')) || 10
    })
    const [total, setTotal] = useState(0)
    // 设置初始数据
    const [datalist, setDatalist] = useState([]);

    const [newcategory, setNewCategory] = useState([])

    //数据搜索展示
    const onSearch = async (value) => {
        // console.log("onSearch", value);
        setUrlParams(`keyword=${value}`);
        // 发起ajax请求，搜索
        getSeachData()

    }
    const changeKeyword = (e) => {
        // console.log("changeKeyword", value)
        // console.log(1, urlParams)
        setKeyword(e.target.value)
        // console.log(2, urlParams)
        // console.log(keyword)
    }

    // const value = keyword;
    //获取搜索的数据
    const getSeachData = async () => {
        console.log('keyword', keyword);
        const { data } = await axios.get('http://120.76.247.5:2001/api/search',
            {
                params: {
                    keyword,
                    // page
                }

            }
        )
        console.log('data', data)

        // 实现滚动加载的功能，每次获取数据后，必须在元数据的基础上增加数据
        const newDatalist = [...data.data.result]
        setDatalist(newDatalist)
        // setTotal(data.data.total)
        console.log('newDatalist', newDatalist)
        // // 设置是否还有新的数据
        // setHasMore(newDatalist.length < data.data.total)

        // // 请求结束后loading改为false
        // setLoading(false);
    }

    // let controller
    //获取数据
    const getData = async () => {
        // controller = new AbortController()
        const { data } = await request.get('/iq', {
            params
        })
        // console.log('data', data);
        setDatalist(data.data.result)
        setTotal(data.data.total)
        // 设置是否还有新的数据
        // setHasMore(newDatalist.length < data.data.total)

        // 请求结束后loading改为false
        // setLoading(false);
    }

    //删除列表项
    const removeItem = useCallback(async (id) => {
        const { data } = await request.delete('/iq/' + id)
        console.log(data);
        if (data.status === 200) {
            message.success('数据删除成功')
            // 刷新页面方案一：重新请求数据
            getData()

            // 刷新页面方案二：修改state达到刷新的效果
            // setDatalist(datalist.filter(item => item._id != id))
        }
    }, [datalist])


    //批量删除
    const [selectIds, setSelectIds] = useState([])
    const removeItems = useCallback(async () => {
        if (selectIds.length === 0) {
            return message.warning('请选择删除的数据');
        }
        const { data } = await request.delete('/iq', {
            data: {
                ids: selectIds
            }
        })
        if (data.status === 200) {
            message.success('数据删除成功')
            getData()
        }
    }, [selectIds])








    // 跳转到添加页面
    const addItem = useCallback(() => {
        navigate('/manage/question/add')
    }, [])
    // 跳转到编辑页面
    const editItem = useCallback((id) => navigate('/manage/question/' + id), [])
    // 跳转到审核页面
    const audit = useCallback((id) => navigate('/manage/question/audit'), [])
    // 跳转分类列表页面
    const categoryEdit = useCallback((id) => navigate('/manage/category/list'), [])

    // 获取分类下拉菜单
    useEffect(() => {
        getData()
        request.get('/category').then(({ data }) => {
            setNewCategory(data.data)
            // console.log('data.data', data.data);
        })
    }, [params])
    //改变选中分类返回筛选数据
    // const [Date, setDate] = useState()
    // const changContent = useCallback(() => {
    //     const Date = datalist.filter((item) => {
    //         return item.category == newcategory.name
    //     })
    //     setDate(Date)
    // }, [])

    const columns = [
        // //自定义单元格内容
        // render: (text, record, index) => {
        //     // text: 当前列数据(dataIndex对应的数据，如无dataIndex,text与record一致)
        //     // record: 当前行数据
        //     // index: 当前索引值
        {
            title: '#',
            key: '_id',
            render(text, record, index) {
                return index + 1
            }
        },
        {
            title: '面试题',
            dataIndex: 'question',
            render(text, record, index) {
                // console.log('record', record);
                const { answer, hot, category, difficulty } = record
                return (
                    <>
                        <h3>{text}</h3>
                        {/* <p> */}
                        {
                            category ? <Button size='small' className='w_space' onClick={categoryEdit}>{category}</Button> : <Button className='w_space' size='small' type="dashed" onClick={categoryEdit}>未分类 </Button>
                        }
                        <span className='w_space'>{hot}浏览 ·</span>
                        <span className='w_space'>{answer}回答 ·</span>
                        <span>难度：{<Rate disabled defaultValue={difficulty} allowHalf />}</span>
                        {/* </p> */}
                    </>
                )
            }
        },
        {
            title: 'tags',
        },
        {
            title: '审核',
            dataIndex: 'checked',
            width: 80,
            render(text, record, index) {
                return text == false ? <Button size='small' onClick={audit}>未审核</Button> : <Button size='small' type='primary' ghost onClick={audit}>已审核</Button>
            }
        },
        {
            title: '时间',
            dataIndex: 'addtime',
            width: 120,
            render(text, record, index) {
                return text.slice(0, 10)
            }
        },
        {
            title: '操作',
            dataIndex: '_id',
            width: 100,
            render(id) {
                return (
                    // <React.Fragment>
                    <Space>
                        <Button ghost type='primary' icon={<FormOutlined />} size="small" onClick={editItem.bind(null, id)}></Button>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItem.bind(null, id)}
                        >
                            <Button danger icon={<DeleteOutlined />} size="small"></Button>

                        </Popconfirm>
                    </Space>
                )
            }
        },
    ]
    //复选框功能
    const rowSelection = {
        onChange(selectedRowKeys) {
            console.log('selectedRowKeys=', selectedRowKeys)
            setSelectIds(selectedRowKeys)
        }
    }

    // 分页功能
    const pagination = {
        total,
        current: params.page,
        pageSize: params.size,
        size: 'small',
        onChange(page, size) {
            setParams({
                page,
                size
            })

            setUrlParams({
                page,
                size
            })
        }
    }

    //数据刷新
    useEffect(() => {
        getData();
        // return function () {
        //     // 取消ajax
        //     controller.abort()
        // }
    }, [params])


    return (
        <div>
            <Search
                addonBefore={<Select defaultValue="HTML" className='search_select' >
                    {

                        newcategory.map((item) => {
                            return <Option key={item._id} value={item.name}>{item.name}</Option>
                        })


                    }
                    {/* <Option value="Option1">Option1</Option>
                    <Option value="Option2">Option2</Option> */}
                </Select>}
                placeholder="输入搜索内容"
                allowClear
                // value={keyword}
                onSearch={onSearch}
                onChange={changeKeyword}
                style={{
                    marginBottom: 20,
                }}
            />
            <Row gutter={20}>
                <Col span={8}>
                    <Button type='primary' icon={<PlusOutlined />} onClick={addItem}>添加</Button>
                </Col>
                <Col span={16} className='text-right'>
                    <Space>
                        <p className='btn'>
                            <Button size='small' type='link' icon={<ImportOutlined />}>导入</Button>
                            <span className='shuxian'></span>
                            <Button size='small' type='link' icon={<ExportOutlined />}>导出</Button>
                        </p>
                        <Popconfirm
                            title="确认删除"
                            onConfirm={removeItems}
                        >
                            <Button danger size='small' icon={<DeleteOutlined />}>批量删除</Button>

                        </Popconfirm>

                    </Space>
                </Col>
            </Row>
            <Table
                style={{ marginTop: 20 }}
                rowKey="_id"
                rowSelection={rowSelection}
                columns={columns}
                dataSource={datalist}
                pagination={pagination}
            />
        </div>

    )
}

export default List;